from uQR import QRCode
from machine import Pin,SPI
import st7789
import network
import socket
import time
import re

led = Pin(2,Pin.OUT)
led.value(1)

def do_connect():
    
    wlan = network.WLAN()
    wlan.active(True)
    if not wlan.isconnected():
        print('connecting to network...')
        wlan.connect('1408', 'zhinengxitong1408')
        i=0
        while not wlan.isconnected():
            print("连接中...{}".format(i))
            i+=1
            time.sleep(1)
    print('network config:', wlan.ipconfig('addr4'))
    return wlan.ifconfig()[0]

def show_qrcode(ip):
    #return 0
    tft=st7789.ST7889_Image(SPI(2,80000000),dc=Pin(2),cs=Pin(5),rst=Pin(15))
    tft.fill(st7789.color565(255,255,255)) #背景设置成白色

    qr=QRCode(border=2)
    qr.add_data('http://{}'.format(ip))
    matrix=qr.get_matrix()

    row_len=len(matrix)
    col_len=len(matrix[0])

    #放大倍数
    scale_rate=8 

    buffer_black = bytearray(scale_rate * scale_rate * 2)  # 每个点pixel有2个字节表示颜色
    buffer_white = bytearray(scale_rate * scale_rate * 2)  # 每个点pixel有2个字节表示颜色
    color_black = st7789.color565(0, 0, 0)
    color_black_byte1 = color_black & 0xFF00 >> 8
    color_black_byte2 = color_black & 0xFF
    color_white = st7789.color565(255, 255, 255)
    color_white_byte1 = color_white & 0xFF00 >> 8
    color_white_byte2 = color_white & 0xFF

    for i in range(0, scale_rate * scale_rate * 2, 2):
        buffer_black[i] = color_black_byte1
        buffer_black[i + 1] = color_black_byte2
        buffer_white[i] = color_white_byte1
        buffer_white[i + 1] = color_white_byte2

    # 循环次数不增加，只增加每次发送的数据量，每次发送scale_rate X scale_rate个点的信息
    for row in range(row_len):
        for col in range(col_len):
            if matrix[row][col]:
                # tft.pixel(row, col, st7789.color565(0, 0, 0))
                tft.show_img(row * scale_rate, col * scale_rate, row * scale_rate + scale_rate - 1, col * scale_rate + scale_rate - 1, buffer_black)
            else:
                # tft.pixel(row, col, st7789.color565(255, 255, 255))
                tft.show_img(row * scale_rate, col * scale_rate, row * scale_rate + scale_rate - 1, col * scale_rate + scale_rate - 1, buffer_white)

                
def tcp_conrtol():
    tcp = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    tcp.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
    tcp.bind(("",80))
    tcp.listen(128)
    while True :
        c_s,c_i = tcp.accept()
        handle_request(c_s)
    tcp.close()
    
def handle_request(c_s):
    r_c = c_s.recv(1024).decode("utf-8")
    print(r_c)
    lines = r_c.splitlines()
    
    r_f_p = re.match(r"[^/]+(/[^ ]*)",lines[0]).group(1)  
    
    if r_f_p =="/":
        if led.value():
            r_f_p = "led_on.html"
        else :
            r_f_p = "led_off.html"
            
    if r_f_p == "/switch_btn":
        if led.value():
            led.value(0)
            r_f_p = "led_off.html"
        else:
            led.value(1)
            request_file_path = "led_on.html"
    
    try:
        with open(r_f_p,"rb") as f:
            content = f.read()
    
    except Exception as ret:
        r_h = "HTTP/1.1 404 Not Found\r\n"
        r_h +="Connection:close\r\n"
        r_h += "Content-Type:text/html;charset=utf-8\r\n"
        r_h += "\r\n"
        
        r_b = "----sorry,the file you need not found----"
        
        res =r_h + r_b
        
        c_s.send(res.encode("utf-8"))
    else :
        r_h ="HTTP/1.1 200 OK\r\n"
        r_h +="Connection:close\r\n"
        r_h += "Content-Type:text/html;charset=utf-8\r\n"
        r_h += "\r\n"
        r_b = content
        res = r_h.encode("utf-8") + r_b
        c_s.send(res)
    c_s.close()
    
def main():
    ip = do_connect()
    show_qrcode(ip)
    tcp_conrtol()

if __name__ =="__main__":
    main()









